﻿using System;
using System.Xml;

namespace Devv.FreshTracker.Entity
{
	[Serializable]
	public class Session
	{
		#region Properties

		public Int64 Id { get; set; }
		public Int32 TempSeconds { get; set; }
		public Double Hours { get; set; }
		public DateTime Date { get; set; }
		public String Notes { get; set; }
		public Task Task { get; set; }

		public String DisplayMember
		{
			get { return ToString(); }
		}

		public Boolean HasMinimumTime
		{
			get { return (Hours > 0.015 || TempSeconds > 60); }
		}

		#endregion

		#region Constructor

		public Session()
		{
			DateTime now = DateTime.Now;

			Id = (now.Second + now.Minute * 60 + now.Hour * 3600) * -1;
		}

		public Session(XmlNode node)
		{
			XmlNamespaceManager ns = new XmlNamespaceManager(node.OwnerDocument.NameTable);
			ns.AddNamespace("ns", FreshBooks.DEFAULT_XMLNS);

			Id = Convert.ToInt64(node.SelectSingleNode("ns:time_entry_id", ns).InnerText);
			Hours = Convert.ToDouble(node.SelectSingleNode("ns:hours", ns).InnerText);
			Date = Convert.ToDateTime(node.SelectSingleNode("ns:date", ns).InnerText);
			Notes = node.SelectSingleNode("ns:notes", ns).InnerText;

			Task = new Task();
			Task.Id = Convert.ToInt64(node.SelectSingleNode("ns:task_id", ns).InnerText);

			Task.Project = new Project();
			Task.Project.Id = Convert.ToInt64(node.SelectSingleNode("ns:project_id", ns).InnerText);

			Task.Project.Client = new Client();
			Task.Project.Client.Id = Convert.ToInt64(node.SelectSingleNode("ns:client_id", ns).InnerText);
		}

		#endregion

		#region Methods

		public Double GetHoursFromTempSeconds()
		{
			return Convert.ToDouble(TempSeconds) / 60 / 60;
		}

		public void SetHoursFromSeconds(Int32 seconds)
		{
			Date = DateTime.Now;
			Hours = Convert.ToDouble(seconds) / 60 / 60;
		}

		public void Round()
		{
			Double r = Hours;

			while (r >= Options.Round)
			{
				r -= Options.Round;
			}

			Hours = Hours + Options.Round - r;
		}

		#endregion

		#region ToString

		public override String ToString()
		{
			return Task.FullDisplayMember + " ("  + Date.ToShortDateString() + " - " + Hours + " " + Messages.Hours + ")";
		}

		#endregion
	}
}